﻿#include "local_server.h"

local_server::local_server(QString listen_name)
{
     this->listen_name=listen_name;
}

local_server::~local_server()
{
  Common::localSocket_MapLock.lockForWrite();
  emit disconnect_Allsocket();
  QMap<local_socket*,M_Socket*>::const_iterator i;
  for (i = Common::localSocket_Map.constBegin(); i != Common::localSocket_Map.constEnd(); ++i) {    //对QMAP进行遍历
       delete i.value();
  }
  Common::localSocket_Map.clear();
  Common::localSocket_MapLock.unlock();
  qDebug()<<"local_server已关闭!";
}

bool local_server::start_server()
{
    if(!listen(listen_name))
    {
        qDebug()<<"本地监听失败!";
        return false;
    }
    else
    {
        qDebug()<<"本地监听成功!";
        return  true;
    }
}


void local_server::incomingConnection(quintptr socketDescriptor)
{
    qDebug()<<"本地计算模块连接成功!";
    local_socket *l_socket=new local_socket(socketDescriptor);
    if(!l_socket->localSocket_init())
    {
        return;
    }
    connect(this,SIGNAL(disconnect_Allsocket()),l_socket,SLOT(disconnect_Allsocket()));
    connect(l_socket,SIGNAL(disconnected()),this,SLOT(delete_localSocket()),Qt::QueuedConnection);
    connect(l_socket,SIGNAL(reply_data(QString,QString,QString)),handlemanage,SLOT(receive(QString,QString,QString)),Qt::QueuedConnection);
    connect(handlemanage,SIGNAL(l_SocketSendData(QString,QString,QString,local_socket*,emit_type,QString)),l_socket,SLOT(l_socketSend(QString,QString,QString,local_socket*,emit_type,QString)),Qt::QueuedConnection);
    l_socket->send_message("计算节点","计算模块状态","");
    M_Socket *m_socket=new M_Socket();
    m_socket->Stype=Lsocket;
    m_socket->l_socket=l_socket;
    Common::localSocket_MapLock.lockForWrite();
    Common::localSocket_Map[l_socket]=m_socket;
    Common::localSocket_MapLock.unlock();
}

void local_server::delete_localSocket()
{
    qDebug()<<"本地计算模块断开连接";
     QList<LocalSocket_SendData>  data;

    QMap  <QString,LocalSocket_SendData>::const_iterator i;
    Common::Localsocket_CaculatedataLock.lockForWrite();
    for (i = Common::Localsocket_Caculatedata.constBegin(); i != Common::Localsocket_Caculatedata.constEnd(); ++i) {    //对QMAP进行遍历
          data.append(i.value());
    }
    Common::Localsocket_Caculatedata.clear();
    Common::Localsocket_CaculatedataLock.unlock();

    Common::Localsocket_unsenddataLock.lockForWrite();
    Common::Localsocket_unsenddata.append(data);
    Common::Localsocket_unsenddataLock.unlock();
    qDebug()<<QString("将未处理完的计算任务放入队列中,数量：%1").arg(data.size());
    local_socket *socket=qobject_cast<local_socket*>(sender());
    Common::localSocket_MapLock.lockForWrite();
    if(Common::localSocket_Map.remove(socket)==0)
    {
        qDebug()<<"没有在map中找到localsocket!!";
    }
    Common::localSocket_MapLock.unlock();
    qDebug()<<"重启本地计算模块";
    emit this->restart_localcaculate();
}

void local_server::set_handle(handle_manage *handlemanage)
{
    this->handlemanage=handlemanage;
}
